/**
 * Copyright &copy; 2012-2016 civet All rights reserved.
 */
package cn.mcsys.myadmin.modules.air.service;

import java.util.List;

import cn.mcsys.myadmin.common.utils.Constant;
import cn.mcsys.myadmin.common.utils.MathUtils;
import cn.mcsys.myadmin.modules.air.entity.AirCar;
import cn.mcsys.myadmin.modules.air.entity.AirRidePoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.mcsys.myadmin.common.persistence.Page;
import cn.mcsys.myadmin.common.service.CrudService;
import cn.mcsys.myadmin.modules.air.entity.AirDriver;
import cn.mcsys.myadmin.modules.air.dao.AirDriverDao;

/**
 * 司机管理Service
 * @author leopold
 * @version 2018-08-13
 */
@Service
@Transactional(readOnly = true)
public class AirDriverService extends CrudService<AirDriverDao, AirDriver> {

	@Autowired
	private AirRidePointService airRidePointService;

	@Autowired
	private AirCarService airCarService;

	public AirDriver get(Integer id) {
		return super.get(id);
	}
	
	public List<AirDriver> findList(AirDriver airDriver) {
		return super.findList(airDriver);
	}
	
	public Page<AirDriver> findPage(Page<AirDriver> page, AirDriver airDriver) {
		return super.findPage(page, airDriver);
	}

	/**
	 * 加入新司机,就在对应的乘车点+1,如果是已有司机换乘车点在对应的乘车点-1,新乘车点+1
	 * @param airDriver
	 */
	@Transactional(readOnly = false)
	public void save(AirDriver airDriver) {
		if (airDriver.getAirCar() != null){
			//新乘车点
			AirCar airCar = airCarService.getAll(airDriver.getAirCar().getId());
			AirRidePoint point = airCar.getAirRidePoint();
			if (airDriver.getIsNewRecord()){
				dao.insert(airDriver);
			}else{
				//获取以前司机对象
				AirCar oldCar = dao.get(airDriver.getId()).getAirCar();
				oldCar = airCarService.getAll(oldCar.getId());
				AirRidePoint oldAirRidePoint = oldCar.getAirRidePoint();
				//旧站点
				oldAirRidePoint.setDriverSum(MathUtils.reduceOne(oldAirRidePoint.getDriverSum()));
				airRidePointService.updateTemplate(oldAirRidePoint);
				dao.update(airDriver);
			}
			point.setDriverSum(MathUtils.addOne(point.getDriverSum()));
			airRidePointService.save(point);
		}else {
			super.save(airDriver);
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(AirDriver airDriver) {
		super.delete(airDriver);
	}

	public void changeIdNumber(Page<AirDriver> page){
		List<AirDriver> list = page.getList();
		for (AirDriver airDriver : list) {
			if(airDriver.getIdNumber() != null && airDriver.getIdNumber().length()>10){
				String before = airDriver.getIdNumber().substring(0,6);
				airDriver.setIdNumber(before + Constant.MANYSTAR);
			}
		}
	}

	public List<AirDriver> findAllDriver() {
		return null;
	}
}